#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <cstdio>
#include <mutex>
#include "mutex.hpp" //将锁进行封装
using namespace std;

#define NUM 3

class threadData
{
public:
    threadData(int number,pthread_mutex_t* lock)
    {
        threadname = "thread-" + to_string(number);
        _lock = lock;
    }
public:
    string threadname;
    pthread_mutex_t* _lock;
};
int tickets = 1000;//用多线程，模拟抢票


void* getTicket(void* args)
{
    threadData* td = static_cast<threadData*>(args);
    const char* name = td->threadname.c_str();
    while(true)
    {
        LockGuard lockguard(td->_lock);
        if(tickets > 0)
        {
            usleep(1000);
            printf("who=%s, get a ticket: %d\n", name,tickets);
            tickets--;
        }
        else 
        {
            break;
        }
        usleep(12);
    }

    return nullptr;
}
int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock,nullptr);
    vector<pthread_t>tids;
    vector<threadData*> thread_datas;
    for(int i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData(i,&lock);
        thread_datas.push_back(td);
        pthread_create(&tid, nullptr, getTicket, thread_datas[i-1]);
        tids.push_back(tid);
    }

    for(int i = 0; i < tids.size(); i++)
    {
        pthread_join(tids[i],nullptr);
        delete  thread_datas[i];
    }
    pthread_mutex_destroy(&lock);
    return 0;
}